/**
 * ztree插件的封装
 */
(function() {

	var $ZTree = function(id, url) {
		this.id = id;
		this.url = url;
		this.onClick = null;
		this.settings = null;
		this.ondblclick=null;
		this.onAsyncSuccess=null;
		this.enableChk=false;
		this.chkStyle="radio";
	};

	$ZTree.prototype = {
		/**
		 * 初始化ztree的设置
		 */
		initSetting : function() {
			var settings = {
				view : {
					dblClickExpand : true,
					selectedMulti : false
				},
				data : {simpleData : {enable : true}},
				callback : {
					onClick : this.onClick,
					onDblClick:this.ondblclick
				},
				check:{
					enable:this.enable,
					chkStyle:this.chkStyle
				}
			};
			return settings;
		},

		/**
		 * 手动设置ztree的设置
		 */
		setSettings : function(val) {
			this.settings = val;
		},

		/**
		 * 初始化ztree
		 */
		init : function() {
			var zNodeSeting = null;
			if(this.settings != null){
				zNodeSeting = this.settings;
			}else{
				zNodeSeting = this.initSetting();
			}
			var zNodes = this.loadNodes();
			$.fn.zTree.init($("#" + this.id), zNodeSeting, zNodes);
		},

		/**
		 * 初始化异步ztree
		 */
		initAsync : function(autoParam,otherParam) {
			var zNodeSeting = null;
			if(this.settings != null){
				zNodeSeting = this.settings;
			}else{
				zNodeSeting = this.initSettingAsync(autoParam,otherParam);
			}
			$.fn.zTree.init($("#" + this.id), zNodeSeting);
		},
		/**
		 * 初始化异步ztree的设置
		 */
		initSettingAsync : function(autoParam,otherParam) {
			var settings = {
				async: {
					enable: true,
					url:this.url,
					autoParam:autoParam?autoParam:null,
					otherParam:otherParam?otherParam:null
				},
				view : {
					dblClickExpand : true,
					selectedMulti : false
				},
				data : {simpleData : {enable : true}},
				callback : {
					onClick : this.onClick,
					onDblClick:this.ondblclick,
					onAsyncSuccess:this.onAsyncSuccess
				}
			};
			return settings;
		},

		/**
		 * 绑定onclick事件
		 */
		bindOnClick : function(func) {
			this.onClick = func;
		},

		/**
		 * 绑定双击事件
		 */
		bindOnDblClick : function(func) {
			this.ondblclick=func;
		},

		/**
		 * 绑定异步加载事件
		 */
		bindOnAsyncSuccess : function(func) {
			this.onAsyncSuccess=func;
		},

		/**
		 * 加载节点
		 */
		loadNodes : function() {
			var zNodes = null;
			var ajax = new $ax(this.url, function(data) {
				zNodes = data;
			}, function(data) {
				Sys.error("加载ztree信息失败!");
			});
			ajax.start();
			return zNodes;
		},

		/**
		 * 获取选中的值
		 */
		getSelectedVal : function(){
			var zTree = $.fn.zTree.getZTreeObj(this.id);
			var nodes = zTree.getSelectedNodes();
			return nodes[0].name;
		},

		/**
		 * 获取ztree对象
		 */
		getObject : function(){
			return zTree = $.fn.zTree.getZTreeObj(this.id);
		},
		setChkStyle:function(chkStyle){
			this.enable=true;
			this.chkStyle=chkStyle;
		},
		setUrl:function(newUrl){
			this.url=newUrl;
		}
	};

	window.$ZTree = $ZTree;

}());